/**
 * Created by sjg on 17/4/3.
 */
var CONFIG = require('../../../../common/config');
var CODE = require('../../../../common/code');
var async = require('async');
var express = require('express');
var router = express.Router();
var moment = require('moment');

var ItbPrintParamModel = require('../../../../common/mysql/mapping/ItbPrintParamModel');
var checkUtil = require('../../util/checkUtil');
var printUtil = require('../../util/printUtil');

//------------------------------------------------------------------
/**
 * 创建默认订单
 *
 * 参数: device	"0 表示从pc来的请求
 * 1 标识一键生成iOS端
 * 2 标识一键生成android端
 * 3  标识一键生成 app 嵌入网页
 * 4 标识一键生成 web 端
 * 5 标识一键生成微信端
 *
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 201 标识利楚商务
 * 301 标识酒单网"
 * 参数: userId	 用户 id
 * 参数: id	 作品 id
 * */
// 测试地址: http://localhost:3000/tp/v1/orders/createDefaultOrder
function createDefaultOrder (req, res, next) {

    //var obj = {"orderId":1221,"orderNo":"5R10118E52FA5"};
    //return printUtil.ret_func_json(1, '成功', obj, res);

    var device = checkUtil.stringFromReq(req, 'device');
    if(!device) {
        return printUtil.ret_func_json(0,CODE.DEVICE_EMPTY,{},res);
    }
    var userId = checkUtil.numberFromReq(req, 'userId');
    if(!userId) {
        return printUtil.ret_func_json(0,CODE.USER_ID_EMPTY,{},res);
    }
    var docId = checkUtil.numberFromReq(req, 'id');
    if(!docId) {
        return printUtil.ret_func_json(0,CODE.DOC_ID_EMPTY,{},res);
    }
    // 此接口
    var orderType = CONFIG.ORDER_TYPE_DB_TRADE;
    // 根据地址创建默认订单
    function create_defalut_order_with_addressId(newDocId, addressId) {
        // 1、获取商品费用等信息：印刷制作费＋设计费＋邮费
        printUtil.getDefaultOrderItemInfo(newDocId, function(error, fee){
            // fee为对象，包含以下属性：productFee, designFee, mailFee
            if(error){
                console.log(error);
                return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
            }
            if(!fee){
                return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
            }
            // 2、创建订单和子订单
            printUtil.createDefaulPrintOrder(device, userId, newDocId, addressId, fee, function(error, newOrderInfo){
                if(error){
                    console.log(error);
                    return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
                }
                if(!newOrderInfo || !newOrderInfo.orderId){
                    return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
                }
                return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,newOrderInfo,res);
            });
        });
    }

    // 0、检查模版信息
    printUtil.getDesignInfoByUserDocId(docId, function(getErr,retInfo){
        if(getErr){
            console.log(getErr);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }

        if(retInfo && retInfo.length>0){
            var designInfo = retInfo[0];
            if(Number(designInfo.publish||'0') == 1){
                // 1、复制用户文档（新文档的purpose设置为2）
                printUtil.copyUserDocForPrintOrder(docId, function (error, newDocId) {
                    if(error){
                        console.log(error);
                        return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
                    }
                    if(!newDocId){
                        return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
                    }

                    // 2、取得用户对应的收货地址（没有则为null）
                    printUtil.getUserAddress(userId, function(error, addressId){
                        if(error){
                            console.log(error);
                            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
                        }

                        // 3.如果存在地址, 则拷贝地址
                        if(addressId == null) {
                            create_defalut_order_with_addressId(newDocId, null);
                        } else {
                            printUtil.copyAddress(addressId, orderType, function(error, newAddressId){
                                if(newAddressId){
                                    create_defalut_order_with_addressId(newDocId, newAddressId)
                                }else{
                                    return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{newAddressId:newAddressId},res);
                                }
                            });
                        }
                    });
                });

            } else {
                return printUtil.ret_func_json(0,'该模版正在升级维护中，请稍后再试',{},res);
            }

        } else {
            return printUtil.ret_func_json(0,'未获取到对应模版信息',{},res);
        }
    });

}
router.get('/createDefaultOrder', createDefaultOrder);
router.post('/createDefaultOrder', createDefaultOrder);
//------------------------------------------------------------------

/**
 *获取用户订单信息(确认订单信息)
 * 参数: device	"0 表示从pc来的请求
 * 1 标识一键生成iOS端
 * 2 标识一键生成android端
 * 3  标识一键生成 app 嵌入网页
 * 4 标识一键生成 web 端
 * 5 标识一键生成微信端
 *
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 201 标识利楚商务
 * 301 标识酒单网"
 * 参数: userId	 用户唯一标识
 * 参数: tradeOrderId	订单 id
 *
 * */
// 测试地址: http://localhost:3000/tp/v1/orders/getPrintOrderInfo
function getPrintOrderInfo(req, res, next) {

    //var obj = {"orderId":1222,"orderNo":"5RE1F15A13249","orderState":10,"addressInfo":{"id":1191,"phone":18696138682,"mobile":18696138682,"name":"刘敏学","prov":{"id":320000,"text":"江苏省"},"city":{"id":320500,"text":"苏州市"},"dist":{"id":320509,"text":"吴江区"},"detail":"光谷创业街102栋栋"},"productInfo":[{"detailOrderId":1218,"id":1627,"fee":10530,"productFee":10000,"designFee":30,"mailFee":500,"qty":1,"printParaId":205,"express":"","tracking_no":"","title":"测试展架图","desc":"测试展架图","size":"800x1800","thumb":"http://itbour-generate.oss-cn-hangzhou.aliyuncs.com/image/U128691/2017/03/21/143831849_CerKnZQFiTkvter5r1yH/0.jpg?x-oss-process=image/resize,m_pad,h_400,w_400,color_f5f5f5","priceCount":"1","price":10000,"unit":"张","min(t2.min)":1}],"totalDesignFee":30,"totalMailFee":500,"totalFee":10530};
    //return printUtil.ret_func_json(1, '成功', obj, res);

    var device = checkUtil.numberFromReq(req, 'device');
    var userId = checkUtil.numberFromReq(req, 'userId');
    var orderId = checkUtil.numberFromReq(req, 'tradeOrderId');
    if(userId == 0 || orderId == 0) {
        return printUtil.ret_func_json(0, '参数错误', {}, res);
    }
    // 串行获取数据
    async.series([
            function(callback){
                // 根据地址和数量计算子订单邮费、并更新总费用
                printUtil.calc_printOrderMailFee(orderId, function(error,data){ callback(error,data)});
            }, // *** 0
            function(callback){
                // 获取订单基本信息
                printUtil.get_printOrderBaseInfo(orderId, function(error,data){ callback(error,data)});
            }, // *** 1
            function(callback){
                // 获取订单地址
                printUtil.get_printAddressInfo(orderId, function(error,data){ callback(error,data)});
            }, // *** 2
            function(callback){
                // 获取订单产品信息
                printUtil.get_tradeOrderDetailsInfo_v5_2(orderId, function(error,data){ callback(error,data)});
            }, // *** 3
            function(callback){
                printUtil.getCouponInfoByTradeOrderId_v5_2(orderId, function(error, data){callback(error,data)});
            }, // *** 4
            function(callback){
                printUtil.chkTradeOrderCanAddAccesstory_v5_2(orderId, function(error, data){callback(error,data)});
            }, // *** 5
            function(callback){
                printUtil.getOrderCouponsCnt_v5_2(userId, orderId, 1, function(error, data){callback(error,data)});
            } // *** 6
        ],

        function(err, results){
            if(err){
                console.log(err);
                return printUtil.ret_func_json(0,'error',{},res);
            }
            if(!results || results.length==0){
                return printUtil.ret_func_json(0,'error',{},res);
            }

            // 地址
            var addressInfo =  null;
            if(results[2]){
                addressInfo = {
                    "id":results[2].addr_id,
                    "phone":results[2].mobile|| results[2].phone,
                    "mobile":results[2].mobile|| results[2].phone,
                    "name":results[2].name,
                    "prov":{"id":results[2].prov,"text":results[2].prov_name},
                    "city":{"id":results[2].city,"text":results[2].city_name},
                    "dist":{"id":results[2].dist,"text":results[2].dist_name},
                    "detail":results[2].detail
                };
            }


            // 总设计费和总运费
            var totalDesignFee = 0;
            var totalMailFee = 0;
            var totalAccesstoryFee = 0;
            for(var i=0;i<results[3].productInfo.length;i++){
                var one = results[3].productInfo[i];
                totalDesignFee += one.designFee;
                totalMailFee += one.mailFee;
            }
            for(var i=0;i<results[3].accesstoryInfo.length; i++){
                var one = results[3].accesstoryInfo[i];
                totalAccesstoryFee += one.accessoryFee;
                totalMailFee += one.mailFee;
            }

            var showAccessory = results[5] ? 1 : 0;

            // 如果当前订单绑定了优惠券, 则可用个数加一
            var couponsCnt = results[6];
            if(results[4] && results[4].id) {
                couponsCnt++;
            }

            var data = {
                "orderId":orderId,
                "orderNo":results[1].order_no,
                "orderState" : results[1].state,
                "addressInfo":addressInfo || {},
                "totalDesignFee":totalDesignFee,
                "totalMailFee":totalMailFee,
                "totalFee":results[1].total_fee,
                "productInfo":results[3].productInfo,
                "showAccessory" : showAccessory,
                "accessoryInfo":results[3].accesstoryInfo,
                "totalAccesstoryFee" : totalAccesstoryFee,
                "couponInfo" : results[4],
                "couponsCnt" : couponsCnt
            };
            return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS, data,res);
        });

}
router.get('/getPrintOrderInfo', getPrintOrderInfo);
router.post('/getPrintOrderInfo', getPrintOrderInfo);

//------------------------------------------------------------------
/**
 * 修改订单信息
 *
 * 参数: device
 * 0 表示从pc来的请求
 * 1 标识一键生成iOS端
 * 2 标识一键生成android端
 * 3  标识一键生成 app 嵌入网页
 * 4 标识一键生成 web 端
 * 5 标识一键生成微信端
 * 101 表示pc美化大师 / 102 表示pc wps / 103 表示wps android / 104表示wps ios
 * 201 标识利楚商务
 * 301 标识酒单网
 *
 * 参数: userId              用户唯一标识
 * 参数: tradeOrderId        商品订单 id
 * 参数[可选]: printParamId   设置商品对应的套餐, 传递则更新订单套餐, 不传递则不更新
 * 参数[可选]: detailOrderId/itemCount  设置商品对应的商品数量, 传递则更新, 不传递则不更新
 * 参数[可选]: accessoryId    设置商品对应的配件, 若传递则更新, 若不传递则不更新
 *                           传递 -1 标识解绑配件, 当前若未绑定配件则认为解绑成功
 *                           传递 正确的配件 id, 则先解绑当前配件, 再绑定新配件
 * 参数[可选]: accessoryCount 设置商品对应的配件数量, 若配件不存在, 不可设置商品数量
 * 参数[可选]: addressId      给订单绑定地址, 在没有地址信息时使用
 *                           用户地址 id, 当订单没有地址时才绑定地址, 每次绑定均拷贝一份作为当前订单地址, 以免共用地址时出错
 *
 * 返回值: {"success":1,"msg":"成功","data":{"orderId":999,"orderNo":"QWERTYUIOP"}}
 *
 * 原接口:
 * 绑定套餐:    /v5/print/bindPrintParamToTradeOrder_v5_2
 * 设置商品数量: /print/modifyGoodsCount
 * 绑定配件:    /v5/print/bindAccessoryToTradeOrder_v5_2
 * 设置配件数量: /v5/print/modifyAccessoryCount_v5_2
 * 绑定地址:    /print/setOrderAddress
 * */
// 测试地址: http://localhost:3000/tp/v1/orders/modifyOrderInfo
function modifyOrderInfo(req, res, next) {

    var device = checkUtil.numberFromReq(req, 'device');
    var userId = checkUtil.numberFromReq(req, 'userId');
    var tradeOrderId = checkUtil.numberFromReq(req, 'tradeOrderId');

    if(userId == 0 || tradeOrderId <= 0) {
        return printUtil.ret_func_json(0, '参数错误', {}, res);
    }

    // 套餐
    var printParamId = checkUtil.numberFromReq(req, 'printParamId');
    // 商品数量
    var detailOrderId = checkUtil.numberFromReq(req, 'detailOrderId');
    var itemCount = checkUtil.numberFromReq(req, 'itemCount');
    // 配件
    var accessoryId = checkUtil.numberFromReq(req, 'accessoryId');
    var accessoryCount = checkUtil.numberFromReq(req, 'accessoryCount');
    // 地址
    var addressId = checkUtil.numberFromReq(req, 'addressId');

    // 串行执行
    async.series([
            function(callback){// ***** 0
                // 检索订单基本信息
                printUtil.get_printOrderBaseInfo(tradeOrderId, function(error, data){
                    callback(error, data);
                });
            },
            function(callback){// ***** 1
                // 绑定套餐
                if(printParamId>0) {
                    printUtil.bindPrintParamToTradeOrder_v5_2(userId, tradeOrderId, printParamId, function(error, data){
                        callback(error,data);
                    });
                } else {
                    callback(null, null);
                }
            },
            function(callback){// ***** 2
                // 设置商品数量
                if(itemCount>0 && detailOrderId>0) {
                    // 更新子订单的数量、金额，以及订单的总金额
                    printUtil.updatePrintOrderCount(tradeOrderId, detailOrderId, itemCount, function(error, newCount){
                        callback(error, newCount);
                    });
                } else {
                    callback(null, null);
                }
            },
            function(callback){// ***** 3
                // 绑定配件
                if(accessoryId != 0) {
                    printUtil.bindAccessoryToTradeOrder_v5_2(userId, tradeOrderId, accessoryId, function (error, data) {
                        callback(error, data);
                    });
                } else {
                    callback(null, null);
                }
            },
            function(callback){// ***** 4
                // 设置配件数量
                if(accessoryCount>0) {
                    printUtil.modifyOrderAccessoryCount_v5_2(userId, tradeOrderId, accessoryCount, function (error, data) {
                        callback(error, data);
                    });
                } else {
                    callback(null, null);
                }
            },
            function(callback){// ***** 5
                // 绑定地址
                if(addressId>0){
                    // 拷贝地址信息
                    var orderType = 10;// 商品订单
                    printUtil.copyAddress(addressId, orderType, function(error, newAddressId){
                        if(newAddressId){
                            // 更新订单地址
                            printUtil.updateOrderAddress(tradeOrderId, orderType, newAddressId, function(error){
                                callback(error, newAddressId);
                            });
                        }else{
                            callback(CODE.OPERATION_FAILED, null);
                        }
                    });
                } else {
                    callback(null, null);
                }
            }
        ],
        // 串行回调返回
        function(err, results) {
            if (err) {
                console.log(err);
                return printUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
            }

            if (!results || results.length == 0 || !results[0]) {
                return printUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
            }
            var data = {orderId: tradeOrderId, orderNo: results[0].order_no||''};
            // 如果有绑定地址则返回绑定后的地址 id
            if(results[5]) {
                data.addressId = results[5];
            }
            // 如果没有修改地址就返回原本的地址 id
            else {
                data.addressId = results[0].addr_id || -1;
            }

            return printUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, data, res);
        }
    );

}
router.get('/modifyOrderInfo', modifyOrderInfo);
router.post('/modifyOrderInfo', modifyOrderInfo);


//------------------------------------------------------------------
/**
 * 获取套餐列表
 * 参数: device	"0 表示从pc来的请求
 * 1 标识一键生成iOS端
 * 2 标识一键生成android端
 * 3  标识一键生成 app 嵌入网页
 * 4 标识一键生成 web 端
 * 5 标识一键生成微信端
 *
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 201 标识利楚商务
 * 301 标识酒单网"
 * 参数: userId	 用户唯一标识
 * 参数: tradeOrderId	 商品订单 id
 *
 * */
// 测试地址: http://localhost:3000/tp/v1/orders/getOrderPrintParams
function getOrderPrintParams(req, res, next) {

    //var obj = {"printParams":[{"id":996,"name":"套餐一","desc":"白卡亚模","price":"1.9/张","thumbs":["http://oss-image.jpg"]}]};
    //return printUtil.ret_func_json(1, '成功', obj, res);

    var device = checkUtil.numberFromReq(req, 'device');
    var userId = checkUtil.numberFromReq(req, 'userId');
    var tradeOrderId = checkUtil.numberFromReq(req, 'tradeOrderId');

    if(userId == 0) {
        return printUtil.ret_func_json(0, '用户Id非法', {}, res);
    }
    if(tradeOrderId == 0) {
        return printUtil.ret_func_json(0, '订单Id非法', {}, res);
    }

    printUtil.getOrderPrintParams_v5_2(userId, tradeOrderId, function(error, data){
        if (error) {
            console.log('tp/v1/orders.js getOrderPrintParams Err: '+error);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }

        return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS, {printParams:data||[]}, res);
    });
}
router.get('/getOrderPrintParams', getOrderPrintParams);
router.post('/getOrderPrintParams', getOrderPrintParams);

//------------------------------------------------------------------
/**
 * 获取商品数量列表
 * 参数: device	"0 表示从pc来的请求
 * 1 标识一键生成iOS端
 * 2 标识一键生成android端
 * 3  标识一键生成 app 嵌入网页
 * 4 标识一键生成 web 端
 * 5 标识一键生成微信端

 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 201 标识利楚商务
 * 301 标识酒单网"
 * 参数: userId	 用户唯一标识
 * 参数: tradeOrderId 商品订单 id ??
 * 参数: printParaId	 商品套餐 id
 *
 * */
// 测试地址: http://localhost:3000/tp/v1/orders/getGoodsPriceCounts
function getGoodsPriceCounts(req, res, next) {

    //var obj = {"counts":[{"minCount":2,"maxCount":10,"price":10,"priceCount":2,"unit":"盒"}], "pricing":10};
    //return printUtil.ret_func_json(1, '成功', obj, res);

    var device = checkUtil.stringFromReq(req, 'device');
    if(!device) {
        return printUtil.ret_func_json(0,CODE.DEVICE_EMPTY,{},res);
    }
    var userId = checkUtil.numberFromReq(req, 'userId');
    if(!userId) {
        return printUtil.ret_func_json(0,CODE.USER_ID_EMPTY,{},res);
    }
    var ppId = checkUtil.numberFromReq(req, 'printParaId');
    if(!ppId) {
        return printUtil.ret_func_json(0,'套餐ID为空',{},res);
    }

    // 检索pp
    var ent = new ItbPrintParamModel({
        pp_id: ppId,
        del_flg: 0
    });
    ent.findFromDB(function(findErr, findData) {
        if (findData && findData.length > 0) {
            var ppInfo = findData[0];

            // 检索价格
            printUtil.getPrintParamQtyPriceInfo(userId,ppId,function(error,data){
                if(error){
                    console.log(error);
                    return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
                }

                return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,{counts:data, pricing:ppInfo.pricing},res);
            });

        } else {
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }
    });
}
router.get('/getGoodsPriceCounts', getGoodsPriceCounts);
router.post('/getGoodsPriceCounts', getGoodsPriceCounts);

//------------------------------------------------------------------
/**
 * 获取商品配件列表
 *
 * 参数: device	"0 表示从pc来的请求
 * 1 标识一键生成iOS端
 * 2 标识一键生成android端
 * 3  标识一键生成 app 嵌入网页
 * 4 标识一键生成 web 端
 * 5 标识一键生成微信端
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 201 标识利楚商务
 * 301 标识酒单网"
 * 参数: userId	 用户唯一标识
 * 参数: tradeOrderId	 商品订单 id
 * */
// 测试地址: http://localhost:3000/tp/v1/orders/getOrderAccessorys
function getOrderAccessorys(req, res, next) {
    //var obj = {"accessorys":[{"id":996,"name":"门型展架","desc":"60cm*160cm","price":"300/个","thumbs":["http://oss-image.jpg"]}]};
    //return printUtil.ret_func_json(1, '成功', obj, res);

    var device = checkUtil.numberFromReq(req, 'device');
    var userId = checkUtil.numberFromReq(req, 'userId');
    var tradeOrderId = checkUtil.numberFromReq(req, 'tradeOrderId');
    var printParamId = checkUtil.numberFromReq(req, 'printParamId');
    if(userId == 0 || tradeOrderId == 0 ) {
        return printUtil.ret_func_json(0, '参数错误', {}, res);
    }
    var pageNum = checkUtil.numberFromReq(req, 'pageNum');
    var pageSize = checkUtil.numberFromReq(req, 'pageSize')||12;

    printUtil.getOrderAccessorys(userId, tradeOrderId, printParamId, pageNum,pageSize, function(error,data){
        if(error){
            return printUtil.ret_func_json(0, CODE.OPERATION_FAILED, data, res);
        }
        // 酒单网必须使用配件, 配件列表不能选择不使用配件
        if(device == 301) {
            data.accessorys.shift();
        }
        return printUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, data, res);
    });
}
router.get('/getOrderAccessorys', getOrderAccessorys);
router.post('/getOrderAccessorys', getOrderAccessorys);
//------------------------------------------------------------------
/**
 * 获取商品配件数量列表
 *
 * 参数: device	"0 表示从pc来的请求
 * 1 标识一键生成iOS端
 * 2 标识一键生成android端
 * 3  标识一键生成 app 嵌入网页
 * 4 标识一键生成 web 端
 * 5 标识一键生成微信端
 *
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 201 标识利楚商务
 * 301 标识酒单网"
 * 参数: userId	 用户唯一标识
 * 参数: tradeOrderId	 商品订单 id
 * */
// 测试地址: http://localhost:3000/tp/v1/orders/getOrderAccessoryCount
function getOrderAccessoryCount(req, res, next) {

    //var obj = {"counts":[{"minCount":2,"maxCount":10,"price":10,"priceCount":2,"unit":"盒"}]};
    //return printUtil.ret_func_json(1, '成功', obj, res);

    var device = checkUtil.numberFromReq(req, 'device');
    var userId = checkUtil.numberFromReq(req, 'userId');
    var tradeOrderId = checkUtil.numberFromReq(req, 'tradeOrderId');
    if(userId == 0 || tradeOrderId == 0 ) {
        return printUtil.ret_func_json(0, '参数错误', {}, res);
    }

    var defaultSize = 6;
    printUtil.getOrderAccessoryCount(userId, tradeOrderId, defaultSize, function(error,data){
        if(error){
            return printUtil.ret_func_json(0, CODE.OPERATION_FAILED, data, res);
        }
        return printUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, data, res);
    });
}
router.get('/getOrderAccessoryCount', getOrderAccessoryCount);
router.post('/getOrderAccessoryCount', getOrderAccessoryCount);

//------------------------------------------------------------------
/**
 * 获取订单详情信息
 *
 * 参数: device	"0 表示从pc来的请求
 * 1 标识一键生成iOS端
 * 2 标识一键生成android端
 * 3  标识一键生成 app 嵌入网页
 * 4 标识一键生成 web 端
 * 5 标识一键生成微信端
 *
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 201 标识利楚商务
 * 301 标识酒单网"
 * 参数: userId	 用户唯一标识
 * 参数: tradeOrderId	 商品订单 id
 * */
// 原接口: /print/getOrderDetail
// 测试地址: http://localhost:3000/tp/v1/orders/getOrderDetail
function getOrderDetail(req, res, next) {
    //var obj = {"orderId":1222,"orderNo":"5RE1F15A13249","state":10,"addressInfo":{"id":1191,"phone":18696138682,"mobile":18696138682,"name":"刘敏学","prov":{"id":320000,"text":"江苏省"},"city":{"id":320500,"text":"苏州市"},"dist":{"id":320509,"text":"吴江区"},"detail":"光谷创业街102栋栋"},"totalDesignFee":30,"totalMailFee":500,"totalFee":10530,"additionalInfo":{"createTime":"2017-04-05 00:15:13","payTime":null,"printTime":null,"mailTime":null,"doneTime":null,"countdownPay":"5分钟后未支付订单将自动取消","countdownDone":null},"logisticsInfo":null,"deliveryInfo":[{"detailOrderId":1218,"name":"","no":""}],"productInfo":[{"detailOrderId":1218,"id":1627,"fee":10530,"productFee":10000,"designFee":30,"mailFee":500,"qty":1,"printParaId":205,"title":"测试展架图","desc":"测试展架图","item_id":76,"size":"800x1800","item_type":4,"printParamName":"测试展架印品套餐","priceCount":"1","price":10000,"unit":"张","MIN(t2.min)":1,"isAccesstory":0,"thumb":"http://itbour-generate.oss-cn-hangzhou.aliyuncs.com/image/U128691/2017/03/21/143831849_CerKnZQFiTkvter5r1yH/0.jpg?x-oss-process=image/resize,m_pad,h_400,w_400,color_f5f5f5"}],"accessoryInfo":[],"couponInfo":{},"totalAccessoryFee":0};
    //return printUtil.ret_func_json(1, '成功', obj, res);

    var device = checkUtil.stringFromReq(req, 'device');
    if(!device) {
        return printUtil.ret_func_json(0,CODE.DEVICE_EMPTY,{},res);
    }
    var userId = checkUtil.numberFromReq(req, 'userId');
    if(!userId) {
        return printUtil.ret_func_json(0,CODE.USER_ID_EMPTY,{},res);
    }
    var orderId = checkUtil.numberFromReq(req, 'tradeOrderId');
    if(!orderId) {
        return printUtil.ret_func_json(0,CODE.ORDER_ID_EMPTY,{},res);
    }

    // 串行获取数据
    async.series([
            function(callback){
                // 获取订单基本信息
                printUtil.get_printOrderBaseInfo(orderId, function(error,data){ callback(error,data)});
            }, // ***0
            function(callback){
                // 获取订单地址
                printUtil.get_printAddressInfo(orderId, function(error,data){ callback(error,data)});
            }, // ***1
            function(callback){
                // 获取订单产品信息
                //printUtil.get_printProductInfo(orderId, function(error,data){ callback(error,data)});
                callback(null,null);
            }, // ***2
            function(callback){
                // 获取订单附加信息
                printUtil.get_additionalInfo(orderId, function(error,data){ callback(error,data)});
            }, // ***3
            function(callback){
                // 获取订单物流信息
                printUtil.get_logisticsInfo(orderId, function(error,data){ callback(error,data)});
            }, // ***4
            function(callback){
                // 获取订单快递公司信息
                printUtil.get_deliveryInfo(orderId, function(error,data){ callback(error,data)});
            }, // ***5
            function(callback){
                printUtil.get_tradeOrderDetailsInfo_v5_2(orderId, function(error,data){callback(error,data)})
            }, // ***6
            function(callback){
                printUtil.getCouponInfoByTradeOrderId_v5_2(orderId, function(error,data){callback(error,data)})
            } // ***7
        ],

        function(err, results){
            if(err){
                console.log(err);
                return printUtil.ret_func_json(0,'error',{},res);
            }
            //if(!results || results.length==0 || !results[0] || !results[2]){
            //    return printUtil.ret_func_json(0,'error',{},res);
            //}
            if(!results || results.length==0 || !results[0] || !results[6]){
                return printUtil.ret_func_json(0,'error',{},res);
            }

            // 地址
            var addressInfo =  null;
            if(results[1]){
                addressInfo = {
                    "id":results[1].addr_id,
                    "phone":results[1].mobile|| results[1].phone,
                    "mobile":results[1].mobile|| results[1].phone,
                    "name":results[1].name,
                    "prov":{"id":results[1].prov,"text":results[1].prov_name},
                    "city":{"id":results[1].city,"text":results[1].city_name},
                    "dist":{"id":results[1].dist,"text":results[1].dist_name},
                    "detail":results[1].detail
                };
            }


            // 总设计费和总运费
            var totalDesignFee = 0;
            var totalMailFee = 0;
            var totalAccesstoryFee = 0;
            //for(var i=0;i<results[2].length;i++){
            //    var one = results[2][i];
            //    totalDesignFee += one.designFee;
            //    totalMailFee += one.mailFee;
            //}
            for(var i=0;i<results[6].productInfo.length;i++){
                var one = results[6].productInfo[i];
                totalDesignFee += one.designFee;
                totalMailFee += one.mailFee;
            }
            for(var i=0;i<results[6].accesstoryInfo.length; i++){
                var one = results[6].accesstoryInfo[i];
                totalAccesstoryFee += one.accessoryFee;
                totalMailFee += one.mailFee;
            }

            var data = {
                "orderId":orderId,
                "orderNo":results[0].order_no,
                "state":results[0].state,
                "addressInfo":addressInfo,
                //"productInfo":results[2],
                "totalDesignFee":totalDesignFee,
                "totalMailFee":totalMailFee,
                "totalFee":results[0].total_fee,
                "additionalInfo":results[3],
                "logisticsInfo":results[4],
                "deliveryInfo":results[5],
                "productInfo":results[6].productInfo,
                "accessoryInfo":results[6].accesstoryInfo,
                "couponInfo" : results[7],
                "totalAccessoryFee" : totalAccesstoryFee
            };

            return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS, data,res);
        }
    );
}
router.get('/getOrderDetail', getOrderDetail);
router.post('/getOrderDetail', getOrderDetail);

//------------------------------------------------------------------
/**
 * 获取用户订单列表
 *
 * 参数: device	"0 表示从pc来的请求
 * 1 标识一键生成iOS端
 * 2 标识一键生成android端
 * 3  标识一键生成 app 嵌入网页
 * 4 标识一键生成 web 端
 * 5 标识一键生成微信端
 *
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 201 标识利楚商务
 * 301 标识酒单网"
 * 参数: userId	 用户唯一标识
 * 参数[可选]: states	"订单状态:10待支付、11已支付、12支付失败、20制作中、30配送中、40完成、50取消’
 * 所需订单状态数组, 如[10, 30]，如果不传则返回全部状态订单"
 * 参数[可选]: withTotalPage
 *
 * 原接口: /v5/users/getUserOrderList_v5_2
 * 测试地址: http://localhost:3000/tp/v1/orders/getUserOrderList
 * */
function getUserOrderList(req, res, next) {
    //var obj ={"orders":[{"orderId":1220,"orderNo":"0102R4DW544U1","state":12,"productInfo":[{"detailOrderId":1216,"id":1623,"fee":2900,"productFee":2900,"designFee":0,"mailFee":0,"qty":2,"printParaId":1,"express":"","tracking_no":"","title":"黑白商务简约名片","desc":"黑白商务简约名片","size":"90x54","thumb":"http://itbour-generate.oss-cn-hangzhou.aliyuncs.com/image/U128720/2017/03/22/200239618_SqtWlm1SNBlqIorZyuVA/0.jpg?x-oss-process=image/resize,m_pad,h_400,w_400,color_f5f5f5","priceCount":"2","price":2900,"unit":"盒","min(t2.min)":1}],"additionalInfo":{"createTime":"2017-03-22 20:02:45","payTime":null,"printTime":null,"mailTime":null,"doneTime":null,"countdownPay":null,"countdownDone":null},"totalDesignFee":0,"totalMailFee":0,"totalFee":2900,"deliveryInfo":{"detailOrderId":1216,"name":"","no":""}},{"orderId":1218,"orderNo":"01R1DW742T503","state":40,"productInfo":[{"detailOrderId":1214,"id":1619,"fee":1,"productFee":1,"designFee":0,"mailFee":0,"qty":1,"printParaId":1,"express":"","tracking_no":"","title":"黑白商务简约名片","desc":"黑白商务简约名片","size":"90x54","thumb":"http://itbour-generate.oss-cn-hangzhou.aliyuncs.com/image/U128720/2017/03/22/191735829_SksH8LtTHxDsrg6213IY/0.jpg?x-oss-process=image/resize,m_pad,h_400,w_400,color_f5f5f5","priceCount":"2","price":2900,"unit":"盒","min(t2.min)":1}],"additionalInfo":{"createTime":"2017-03-22 19:17:42","payTime":null,"printTime":null,"mailTime":null,"doneTime":"2017-03-22 19:23:13","countdownPay":null,"countdownDone":null},"totalDesignFee":0,"totalMailFee":0,"totalFee":1,"deliveryInfo":{"detailOrderId":1214,"name":"","no":""}},{"orderId":1217,"orderNo":"0RD115W0T2092","state":40,"productInfo":[{"detailOrderId":1213,"id":1617,"fee":2900,"productFee":2900,"designFee":0,"mailFee":0,"qty":2,"printParaId":1,"express":"","tracking_no":"","title":"蓝色lowpoly通用名片","desc":"蓝色lowpoly通用名片","size":"90x54","thumb":"http://itbour-generate.oss-cn-hangzhou.aliyuncs.com/image/U128720/2017/03/22/191456205_dHyCMmiGxZl0tLw3WUQj/0.jpg?x-oss-process=image/resize,m_pad,h_400,w_400,color_f5f5f5","priceCount":"2","price":2900,"unit":"盒","min(t2.min)":1}],"additionalInfo":{"createTime":"2017-03-22 19:15:02","payTime":null,"printTime":null,"mailTime":null,"doneTime":"2017-03-22 19:25:55","countdownPay":null,"countdownDone":null},"totalDesignFee":0,"totalMailFee":0,"totalFee":2900,"deliveryInfo":{"detailOrderId":1213,"name":"","no":""}},{"orderId":1206,"orderNo":"01R0D153W4S94","state":40,"productInfo":[{"detailOrderId":1202,"id":1584,"fee":1,"productFee":1,"designFee":0,"mailFee":0,"qty":1,"printParaId":1,"express":"","tracking_no":"","title":"黑白商务简约名片","desc":"黑白商务简约名片","size":"90x54","thumb":"http://itbour-generate.oss-cn-hangzhou.aliyuncs.com/image/U128720/2017/03/22/180129687_W094lnpYeaik1V7UYbq6/0.jpg?x-oss-process=image/resize,m_pad,h_400,w_400,color_f5f5f5","priceCount":"2","price":2900,"unit":"盒","min(t2.min)":1}],"additionalInfo":{"createTime":"2017-03-22 18:01:53","payTime":"2017-03-22 18:59:22","printTime":null,"mailTime":null,"doneTime":"2017-03-22 19:14:22","countdownPay":null,"countdownDone":null},"totalDesignFee":0,"totalMailFee":0,"totalFee":1,"deliveryInfo":{"detailOrderId":1202,"name":"","no":""}},{"orderId":1200,"orderNo":"012R0D3W766R4","state":40,"productInfo":[{"detailOrderId":1196,"id":1565,"fee":2900,"productFee":2900,"designFee":0,"mailFee":0,"qty":2,"printParaId":1,"express":"","tracking_no":"","title":"黑白商务简约名片","desc":"黑白商务简约名片","size":"90x54","thumb":"http://itbour-generate.oss-cn-hangzhou.aliyuncs.com/image/U128720/2017/03/22/172031450_Sggw0ZNhyLEjPrGqwcFo/0.jpg?x-oss-process=image/resize,m_pad,h_400,w_400,color_f5f5f5","priceCount":"2","price":2900,"unit":"盒","min(t2.min)":1}],"additionalInfo":{"createTime":"2017-03-22 17:20:37","payTime":null,"printTime":null,"mailTime":null,"doneTime":"2017-03-22 19:24:41","countdownPay":null,"countdownDone":null},"totalDesignFee":0,"totalMailFee":0,"totalFee":2900,"deliveryInfo":{"detailOrderId":1196,"name":"","no":""}},{"orderId":1199,"orderNo":"011RD7W1333R6","state":40,"productInfo":[{"detailOrderId":1195,"id":1563,"fee":1,"productFee":1,"designFee":0,"mailFee":0,"qty":1,"printParaId":1,"express":"","tracking_no":"","title":"灰金个性商务名片","desc":"灰金个性商务名片","size":"90x54","thumb":"http://itbour-generate.oss-cn-hangzhou.aliyuncs.com/image/U128720/2017/03/22/171707595_VHK1ZJWiCui8I7HgkxgT/0.jpg?x-oss-process=image/resize,m_pad,h_400,w_400,color_f5f5f5","priceCount":"2","price":2900,"unit":"盒","min(t2.min)":1}],"additionalInfo":{"createTime":"2017-03-22 17:17:13","payTime":null,"printTime":null,"mailTime":null,"doneTime":"2017-03-22 19:34:15","countdownPay":null,"countdownDone":null},"totalDesignFee":0,"totalMailFee":0,"totalFee":1,"deliveryInfo":{"detailOrderId":1195,"name":"","no":""}},{"orderId":1197,"orderNo":"0R1D115W38R54","state":12,"productInfo":[{"detailOrderId":1193,"id":1559,"fee":21000,"productFee":21000,"designFee":0,"mailFee":0,"qty":500,"printParaId":101,"express":"","tracking_no":"","title":"黑白简约企业宣传单","desc":"黑白简约企业宣传单","size":"210x285","thumb":"http://itbour-generate.oss-cn-hangzhou.aliyuncs.com/image/U128720/2017/03/22/171148472_mgnPvkiL49850mJo0z6w/0.jpg?x-oss-process=image/resize,m_pad,h_400,w_400,color_f5f5f5","priceCount":"500","price":21000,"unit":"张","min(t2.min)":1}],"additionalInfo":{"createTime":"2017-03-22 17:11:53","payTime":null,"printTime":null,"mailTime":null,"doneTime":null,"countdownPay":null,"countdownDone":null},"totalDesignFee":0,"totalMailFee":0,"totalFee":21000,"deliveryInfo":{"detailOrderId":1193,"name":"","no":""}},{"orderId":1196,"orderNo":"0R10D2W3831R6","state":10,"productInfo":[{"detailOrderId":1191,"id":1557,"fee":2900,"productFee":2900,"designFee":0,"mailFee":0,"qty":2,"printParaId":1,"express":"","tracking_no":"","title":"黑白商务简约名片","desc":"黑白商务简约名片","size":"90x54","thumb":"http://itbour-generate.oss-cn-hangzhou.aliyuncs.com/image/U128720/2017/03/22/170232889_Fki74CTfuC1cv4B0NHah/0.jpg?x-oss-process=image/resize,m_pad,h_400,w_400,color_f5f5f5","priceCount":"2","price":2900,"unit":"盒","min(t2.min)":1}],"additionalInfo":{"createTime":"2017-03-22 17:02:38","payTime":null,"printTime":null,"mailTime":null,"doneTime":null,"countdownPay":null,"countdownDone":null},"totalDesignFee":0,"totalMailFee":0,"totalFee":2900,"deliveryInfo":{"detailOrderId":1191,"name":"","no":""}},{"orderId":1195,"orderNo":"0R1D55W56Q600","state":12,"productInfo":[{"detailOrderId":1190,"id":1555,"fee":2900,"productFee":2900,"designFee":0,"mailFee":0,"qty":2,"printParaId":1,"express":"","tracking_no":"","title":"灰金个性商务名片","desc":"灰金个性商务名片","size":"90x54","thumb":"http://itbour-generate.oss-cn-hangzhou.aliyuncs.com/image/U128720/2017/03/22/165550691_aMtwbV0GJJmjiFSYNWEh/0.jpg?x-oss-process=image/resize,m_pad,h_400,w_400,color_f5f5f5","priceCount":"2","price":2900,"unit":"盒","min(t2.min)":1}],"additionalInfo":{"createTime":"2017-03-22 16:55:56","payTime":null,"printTime":null,"mailTime":null,"doneTime":null,"countdownPay":null,"countdownDone":null},"totalDesignFee":0,"totalMailFee":0,"totalFee":2900,"deliveryInfo":{"detailOrderId":1190,"name":"","no":""}},{"orderId":1194,"orderNo":"01R4D7096W2Q4","state":10,"productInfo":[{"detailOrderId":1189,"id":1553,"fee":2900,"productFee":2900,"designFee":0,"mailFee":0,"qty":2,"printParaId":1,"express":"","tracking_no":"","title":"黑白商务简约名片","desc":"黑白商务简约名片","size":"90x54","thumb":"http://itbour-generate.oss-cn-hangzhou.aliyuncs.com/image/U128720/2017/03/22/164655582_sX15IKTwejnkHGGWCrR4/0.jpg?x-oss-process=image/resize,m_pad,h_400,w_400,color_f5f5f5","priceCount":"2","price":2900,"unit":"盒","min(t2.min)":1}],"additionalInfo":{"createTime":"2017-03-22 16:47:09","payTime":null,"printTime":null,"mailTime":null,"doneTime":null,"countdownPay":null,"countdownDone":null},"totalDesignFee":0,"totalMailFee":0,"totalFee":2900,"deliveryInfo":{"detailOrderId":1189,"name":"","no":""}}],"currentPage":0,"totalPage":3};
    //return printUtil.ret_func_json(1, '成功', obj, res);

    var device = checkUtil.stringFromReq(req, 'device');
    if(!device) {
        return printUtil.ret_func_json(0,CODE.DEVICE_EMPTY,{},res);
    }
    var userId = checkUtil.numberFromReq(req, 'userId');
    if(!userId) {
        return printUtil.ret_func_json(0,CODE.USER_ID_EMPTY,{},res);
    }
    var states = checkUtil.stringFromReq(req, 'states');
    if(states) {
        states = JSON.parse(states);
    }
    var pageNum = checkUtil.numberFromReq(req, 'pageNum') || 0;
    var pageSize = checkUtil.numberFromReq(req, 'pageSize') || 12;
    var withTotalPage = checkUtil.numberFromReq(req, 'withTotalPage');

    printUtil.getPrintOrderList(userId, states, pageNum, pageSize, function(error,data){
        if(error){
            console.log(error);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }
        var ret = {orders : data || [], currentPage : pageNum};
        // 不需要总页数
        if(!withTotalPage) {
            return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,ret,res);
        }
        // 获取总页数
        printUtil.getPrintOrderListCnt(userId, states, function(error, count){
            if(error){
                console.log(error);
                return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
            }
            ret.totalPage = Math.floor((count-1)/pageSize)+1;
            return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,ret,res);
        });
    });
}
router.get('/getUserOrderList', getUserOrderList);
router.post('/getUserOrderList', getUserOrderList);

//------------------------------------------------------------------
/**
 * 确认收货
 *
 * 参数: device	"0表示从p0 表示从pc来的请求
 * 1 标识一键生成iOS端
 * 2 标识一键生成android端
 * 3  标识一键生成 app 嵌入网页
 * 4 标识一键生成 web 端
 * 5 标识一键生成微信端
 *
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 201 标识利楚商务
 * 301 标识酒单网c来的请求1表示ios/2表示android/101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios"
 * 参数: userId	用户唯一标识
 * 参数:  tradeOrderId	 商品订单 id
 *
 * 原接口: /print/confirmOrder
 * 测试地址: http://localhost:3000/tp/v1/orders/confirmOrder
 * */
function confirmOrder(req, res, next) {
    var device = checkUtil.stringFromReq(req, 'device');
    if(!device) {
        return printUtil.ret_func_json(0,CODE.DEVICE_EMPTY,{},res);
    }
    var userId = checkUtil.numberFromReq(req, 'userId');
    if(!userId) {
        return printUtil.ret_func_json(0,CODE.USER_ID_EMPTY,{},res);
    }
    var orderId = checkUtil.numberFromReq(req, 'tradeOrderId');
    if(!orderId) {
        return printUtil.ret_func_json(0,CODE.ORDER_ID_EMPTY,{},res);
    }

    printUtil.confirmOrder(userId,orderId,function(error){
        if(error){
            console.log(error);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }

        return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,{},res);
    });
}
router.get('/confirmOrder', confirmOrder);
router.post('/confirmOrder', confirmOrder);

//------------------ 微信端 获取订单可用优惠券列表--------------------------
/**
 * 获取当前订单的优惠券列表(可用/不可用)
 * 参数:device	"0 表示从pc来的请求
 * 1 表示ios
 * 2 表示android
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 3 标识app 嵌入网页
 * 4 标识网站 web 端"
 * 参数: uuid	 设备唯一标识
 * 参数: userId	用户唯一标识
 * 参数: tradeOrderId	 商品订单 id
 * 参数: conformOrder	0 标示获取订单不可使用的优惠券, 1 标示获取可订单可使用的优惠券
 * 注意: 绑定到当前订单的优惠券视为可用优惠券
 * 返回值:
 * {
    "success":1,
    "msg":"成功",
    "data":{
        "coupons":[
            {
                "id":986,
                "code":"QWERTPOIUYEV",
                "type_desc":"抵扣券",
                "discount_desc":"5.0元",
                "trade_type":20,
                "expiry_time":"2017-03-05",
                "coupon_desc":"暂不抵扣运费",
                "reason":""
            }
        ]
    }
 }
 * 测试地址: http://localhost:3000/tp/v1/orders/getOrderCoupons?device=1&userId=128685&tradeOrderId=1&conformOrder=1
 * */
function getOrderCoupons(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var uuid = checkUtil.stringFromReq(req, 'uuid');
    var userId = checkUtil.numberFromReq(req, 'userId');
    var tradeOrderId = checkUtil.numberFromReq(req, 'tradeOrderId');
    var conformOrder = checkUtil.numberFromReq(req, 'conformOrder');
    if(userId == 0 || tradeOrderId == 0) {
        return printUtil.ret_func_json(0, '参数错误', {}, res);
    }
    printUtil.getOrderCoupons_v5_2(userId, tradeOrderId, conformOrder, function (error, data) {
        if (error) {
            console.log('v5/print.js getOrderCoupons_v5_2 Err: '+error);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }
        // 获取1已绑定到当前订单的优惠券
        printUtil.getCouponInfoByTradeOrderId_v5_2(tradeOrderId, function(error1, coupon){
            if(error1) {
                console.log('v5/print.js getOrderCoupons_v5_2 Err 1: '+error1);
                return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
            }
            coupon.expiry_time = moment(coupon.expiry_time).format('YYYY-MM-DD');
            // 订单没有绑定的优惠券无需处理
            if (!coupon || !coupon.id) {
                return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS, {coupons:data||[]}, res);
            }
            // 订单绑定有优惠券, 处理优惠券
            coupon = printUtil.genCouponRetInfo(coupon, userId, 0);

            var coupons = data || [];
            // 如果获取订单可用优惠券则添加当前优惠券
            if (conformOrder) {
                coupons.unshift(coupon); // 将当前订单绑定的优惠券放到第一个
                return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS, {coupons:coupons}, res);
            }
            // 否则, 移除
            if(coupons.length > 0) {
                for(var i = 0; i < coupons.length; i++) {
                    var one = coupons[i];
                    // 一个订单只能绑定一个优惠券, 所以找到删除即可
                    if(one.id == coupon.id) {
                        coupons.splice(i, 1); break;
                    }
                }
            }
            return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS, {coupons:coupons}, res);
        })
    });
}
router.get('/getOrderCoupons', getOrderCoupons);
router.post('/getOrderCoupons', getOrderCoupons);

//-----------------微信端 订单绑定/解绑优惠券接口 ---------------------
/**
 * 绑定/解绑优惠券至订单
 * 参数:device	"0 表示从pc来的请求
 * 1 表示ios
 * 2 表示android
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 3 标识app 嵌入网页
 * 4 标识网站 web 端"
 * 参数: uuid	 设备唯一标识
 * 参数: userId	用户唯一标识
 * 参数; couponId	优惠券 id
 * 参数: tradeOrderId	 商品订单 id
 * 注意: 	"若订单已存在优惠券, 则先解绑优惠券再重新绑定
 *          若不使用优惠券则 传递 couponId 为 -1"
 * 测试地址: http://localhost:3000/tp/v1/orders/bindCouponToTradeOrder?device=1&userId=128685&tradeOrderId=1&couponId=1
 * */

function bindCouponToTradeOrder(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var uuid = checkUtil.stringFromReq(req, 'uuid');
    var userId = checkUtil.numberFromReq(req, 'userId');
    var tradeOrderId = checkUtil.numberFromReq(req, 'tradeOrderId');
    var couponId = checkUtil.numberFromReq(req, 'couponId');

    if(userId == 0 || tradeOrderId == 0 || couponId == 0) {
        return printUtil.ret_func_json(0, '参数错误', {}, res);
    }

    printUtil.bindCouponToTradeOrder_v5_2(userId, tradeOrderId, couponId, function (error, data) {
        if (error) {
            console.log('v5/print.js bindCouponToTradeOrder_v5_2 Err: '+error);
            var errMsg = CODE.OPERATION_FAILED;
            if(typeof error === "string") {
                errMsg = error;
            }
            return printUtil.ret_func_json(0,errMsg,{},res);
        }

        return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,{},res);
    });
}
router.get('/bindCouponToTradeOrder', bindCouponToTradeOrder);
router.post('/bindCouponToTradeOrder', bindCouponToTradeOrder);
//------------------------------------------------------------------
module.exports = router;

